package com.wocai.jrt.orgadmin.stats.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Symbol;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Series;
import com.vteba.utils.common.BigDecimalUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.employee.bean.EmpGroupTreeBean;
import com.wocai.jrt.orgadmin.employee.model.EmployeeGroup;
import com.wocai.jrt.orgadmin.employee.model.Org;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeGroupService;
import com.wocai.jrt.orgadmin.employee.service.spi.OrgService;
import com.wocai.jrt.orgadmin.stats.bean.GroupStatsReqBean;
import com.wocai.jrt.orgadmin.stats.service.spi.GroupStatsJobService;
import com.wocai.jrt.orgadmin.stats.service.spi.GroupStatsService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

@Controller
@RequestMapping("/groupStats")
public class GroupStatsAction extends GenericAction<EmployeeGroup> {
	private static final Logger LOGGER = LoggerFactory.getLogger(GroupStatsAction.class);

	@Inject
	private GroupStatsService groupStatsServiceImpl;
	@Inject
	private EmployeeGroupService employeeGroupServiceImpl;
	@Inject
	private OrgService orgServiceImpl;
	@Inject
	private GroupStatsJobService groupStatsJobServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 刷新缓存
	 * 
	 * @return
	 */
	@RequestMapping("/cache")
	public String cache() {
		groupStatsJobServiceImpl.groupStatsServiceCount();
		return "stats/employeeGroupStats/dayStats";
	}

	/**
	 * 跳转到按天统计页面
	 * 
	 * @return
	 */
	@RequestMapping("/day")
	public String day() {
		return "stats/employeeGroupStats/dayStats";
	}

	/**
	 * 跳转到按月统计页面
	 * 
	 * @return
	 */
	@RequestMapping("/month")
	public String month() {
		return "stats/employeeGroupStats/monthStats";
	}

	/**
	 * 跳转到按年统计页面
	 * 
	 * @return
	 */
	@RequestMapping("/year")
	public String year() {
		return "stats/employeeGroupStats/yearStats";
	}

	@ResponseBody
	@RequestMapping("/tree")
	public EmpGroupTreeBean tree() {
		EmpGroupTreeBean empGroupTreeBean = null;
		try {
			empGroupTreeBean = employeeGroupServiceImpl.plannerTree(UserUtils.getOrgId());
		} catch (Exception e) {
			LOGGER.error("get resource tree error, errorMsg=[{}].", e.getMessage());
		}
		return empGroupTreeBean;
	}

	/**
	 * 按日统计页面
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryDay")
	public JsonBean queryDay(@RequestBody GroupStatsReqBean reqBean) {
		JsonBean json = new JsonBean();
		try {
			// 获取数据
			if (null == reqBean.getBeginDate() || null == reqBean.getEndDate()) {// 默认的时间
				DateTime dateTime = new DateTime();
				reqBean.setBeginDate(dateTime.minusDays(6).toDate());
				reqBean.setEndDate(dateTime.toDate());
			}
			DateTime beginDateTime = new DateTime(reqBean.getBeginDate());
			DateTime endDateTime = new DateTime(reqBean.getEndDate());
			// 选择的时间超过一个月，前端限制了，后端再判断一下
			if (endDateTime.isAfter(beginDateTime.plusMonths(1))) {
				LOGGER.info("groupStats querDay too much data!");
				json.setCode(0);
				json.setMessage("请选择少于一个月的时间区间！");
				return json;
			}
			LOGGER.info("groupStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			ArrayList<String> groupIdList = new ArrayList<String>();
			String[] groupString = null;
			if (null != reqBean.getGroupId()) {
				groupString = reqBean.getGroupId().split(",");
			}
			if (null != groupString) {
				for (int i = 0; i < groupString.length; i++) {
					if (!(groupString[i].equals("root"))) {
						groupIdList.add(groupString[i]);
					}
				}
			}
			if (null == groupIdList || 0 == groupIdList.size()) {// 默认团队
				groupIdList = new ArrayList<String>();
				EmployeeGroup employeeGroup = new EmployeeGroup();
				employeeGroup.setOrgId(UserUtils.getOrgId());
				employeeGroup.setDeleted(false);
				employeeGroup.setPlannerGroup(true);
				List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
						.queryList(employeeGroup);
				if (null == employeeGroupList) {
					json.setCode(0);
					json.setMessage("您的机构下没有可用的理财师团队！");
					return json;
				}
				for (int i = 0; i < employeeGroupList.size(); i++) {
					groupIdList.add(employeeGroupList.get(i).getId());
				}
			}
			LOGGER.info("groupStats querDay groupId = [{}]", groupIdList.toString());

			List<Option> optionList = queryGroupPerformance(beginDateTime, endDateTime, groupIdList);
			json.setCode(1);
			json.setData(optionList);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("groupStats querDay error,msg = [{}]", e.getMessage());
			json.setCode(0);
			json.setMessage("oh no,服务器出错了！");
			return json;
		}
	}

	/**
	 * 按月统计页面
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryMonth")
	public JsonBean queryMonth(@RequestBody GroupStatsReqBean reqBean) {
		JsonBean json = new JsonBean();
		try {
			// 获取数据
			if (null == reqBean.getBeginDate() || null == reqBean.getEndDate()) {// 默认的时间
				DateTime dateTime = new DateTime();
				reqBean.setBeginDate(dateTime.minusMonths(5).toDate());
				reqBean.setEndDate(dateTime.toDate());
			}
			DateTime beginDateTime = new DateTime(reqBean.getBeginDate());
			DateTime endDateTime = new DateTime(reqBean.getEndDate());
			if (beginDateTime.isAfter(endDateTime)) {
				LOGGER.info("groupStats queryMonth datetime err!");
				json.setCode(0);
				json.setMessage("开始时间不能晚于结束时间！");
				return json;
			}
			// 选择的时间超过一年，前端限制了，后端再判断一下
			if (endDateTime.isAfter(beginDateTime.plusMonths(12))) {
				LOGGER.info("groupStats queryMonth too much data!");
				json.setCode(0);
				json.setMessage("请选择少于一年的时间区间！");
				return json;
			}
			LOGGER.info("groupStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			ArrayList<String> groupIdList = new ArrayList<String>();
			String[] groupString = null;
			if (null != reqBean.getGroupId()) {
				groupString = reqBean.getGroupId().split(",");
			}
			if (null != groupString) {
				for (int i = 0; i < groupString.length; i++) {
					if (!(groupString[i].equals("root"))) {
						groupIdList.add(groupString[i]);
					}
				}
			}
			if (null == groupIdList || 0 == groupIdList.size()) {// 默认团队
				groupIdList = new ArrayList<String>();
				EmployeeGroup employeeGroup = new EmployeeGroup();
				employeeGroup.setOrgId(UserUtils.getOrgId());
				employeeGroup.setDeleted(false);
				employeeGroup.setPlannerGroup(true);
				List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
						.queryList(employeeGroup);
				if (null == employeeGroupList) {
					json.setCode(0);
					json.setMessage("您的机构下没有可用的理财师团队！");
					return json;
				}
				for (int i = 0; i < employeeGroupList.size(); i++) {
					groupIdList.add(employeeGroupList.get(i).getId());
				}
			}
			LOGGER.info("groupStats querDay groupId = [{}]", groupIdList.toString());

			List<Option> optionList = queryGroupPerformanceMonth(beginDateTime, endDateTime,
					groupIdList);
			json.setCode(1);
			json.setData(optionList);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("groupStats querDay error,msg = [{}]", e.getMessage());
			json.setCode(0);
			json.setMessage("oh no,服务器出错了！");
			return json;
		}
	}

	/**
	 * 按年统计页面
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryYear")
	public JsonBean queryYear(@RequestBody GroupStatsReqBean reqBean) {
		JsonBean json = new JsonBean();
		try {
			// 获取数据
			if (null == reqBean.getBeginDate() || null == reqBean.getEndDate()) {// 默认的时间
				Org org = orgServiceImpl.get(UserUtils.getOrgId());
				reqBean.setBeginDate(org.getCreateTime());
				reqBean.setEndDate(new Date());
			}
			DateTime beginDateTime = new DateTime(reqBean.getBeginDate());
			DateTime endDateTime = new DateTime(reqBean.getEndDate());
			if (beginDateTime.isAfter(endDateTime)) {
				LOGGER.info("groupStats queryMonth datetime err!");
				json.setCode(0);
				json.setMessage("开始时间不能晚于结束时间！");
				return json;
			}
			// 选择的时间超过一年，前端限制了，后端再判断一下
			// if (endDateTime.isAfter(beginDateTime.plusMonths(12))) {
			// LOGGER.info("groupStats queryMonth too much data!");
			// json.setCode(0);
			// json.setMessage("请选择少于一年的时间区间！");
			// return json;
			// }
			LOGGER.info("groupStats querDay beginDate = [{}], endDate = [{}]", beginDateTime,
					endDateTime);
			ArrayList<String> groupIdList = new ArrayList<String>();
			String[] groupString = null;
			if (null != reqBean.getGroupId()) {
				groupString = reqBean.getGroupId().split(",");
			}
			if (null != groupString) {
				for (int i = 0; i < groupString.length; i++) {
					if (!(groupString[i].equals("root"))) {
						groupIdList.add(groupString[i]);
					}
				}
			}
			if (null == groupIdList || 0 == groupIdList.size()) {// 默认团队
				groupIdList = new ArrayList<String>();
				EmployeeGroup employeeGroup = new EmployeeGroup();
				employeeGroup.setOrgId(UserUtils.getOrgId());
				employeeGroup.setDeleted(false);
				employeeGroup.setPlannerGroup(true);
				List<EmployeeGroup> employeeGroupList = employeeGroupServiceImpl
						.queryList(employeeGroup);
				if (null == employeeGroupList) {
					json.setCode(0);
					json.setMessage("您的机构下没有可用的理财师团队！");
					return json;
				}
				for (int i = 0; i < employeeGroupList.size(); i++) {
					groupIdList.add(employeeGroupList.get(i).getId());
				}
			}
			LOGGER.info("groupStats querDay groupId = [{}]", groupIdList.toString());

			List<Option> optionList = queryGroupPerformanceYear(beginDateTime, endDateTime,
					groupIdList);
			json.setCode(1);
			json.setData(optionList);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("groupStats querDay error,msg = [{}]", e.getMessage());
			json.setCode(0);
			json.setMessage("oh no,服务器出错了！");
			return json;
		}
	}

	private List<Option> queryGroupPerformanceYear(DateTime beginDateTime, DateTime endDateTime,
			ArrayList<String> groupIdList) {
		// 时间“x轴”
		DateTimeFormatter formatterYear = DateTimeFormat.forPattern("yyyy");
		List<String> xList = new ArrayList<String>();
		DateTime tempDateTime = beginDateTime;
		xList.add(tempDateTime.toString(formatterYear));
		tempDateTime = tempDateTime.plusYears(1);
		while ((tempDateTime.toString(formatterYear).compareTo(endDateTime.toString(formatterYear)) <= 0)) {
			xList.add(tempDateTime.toString(formatterYear));
			tempDateTime = tempDateTime.plusYears(1);
		}
		LOGGER.info("groupStats querDay xDateList = [{}]", xList);
		// 团队业绩数据“曲线”
		List<Series> lines = new ArrayList<Series>();// 曲线
		List<String> legend = new ArrayList<String>();// 每个团队的名字
		for (int i = 0; i < groupIdList.size(); i++) {
			EmployeeGroup employeeGroup = employeeGroupServiceImpl.get(groupIdList.get(i));
			legend.add(employeeGroup.getGroupName());
			tempDateTime = beginDateTime;
			List<Double> xData = new ArrayList<Double>();
			tempDateTime = beginDateTime;
			Double yearSales = groupStatsServiceImpl.queryGroupSalesPerformanceYear(
					groupIdList.get(i), tempDateTime.toString(formatterYear));
			xData.add(BigDecimalUtils.divide(yearSales, 10000D, 2));
			tempDateTime = tempDateTime.plusYears(1);
			while ((tempDateTime.toString(formatterYear).compareTo(
					endDateTime.toString(formatterYear)) <= 0)) {
				yearSales = groupStatsServiceImpl.queryGroupSalesPerformanceYear(
						groupIdList.get(i), tempDateTime.toString(formatterYear));
				xData.add(BigDecimalUtils.divide(yearSales, 10000D, 2));
				tempDateTime = tempDateTime.plusYears(1);
			}
			Series line = new Line().smooth(true).name(employeeGroup.getGroupName())
					.symbol(Symbol.circle).data(xData.toArray());
			lines.add(line);
		}
		// 封装option
		Option option = new Option();
		option.title().text("销售业绩统计");
		option.tooltip().trigger(Trigger.axis);
		option.toolbox().show(true).feature(Tool.saveAsImage);
		option.calculable(true);
		option.legend(legend.toArray());
		// CategoryAxis xAxis = new
		// CategoryAxis().boundaryGap(false).data(xList.toArray());
		CategoryAxis xAxis = new CategoryAxis().data(xList.toArray()).name("日期");
		option.xAxis(xAxis);
		ValueAxis yAxis = new ValueAxis().name("销售业绩（万元）");
		option.yAxis(yAxis);
		option.series(lines);

		// 团队新增投资人数据“曲线”
		List<Series> lines2 = new ArrayList<Series>();
		List<String> legend2 = new ArrayList<String>();
		for (int i = 0; i < groupIdList.size(); i++) {
			EmployeeGroup employeeGroup = employeeGroupServiceImpl.get(groupIdList.get(i));
			legend2.add(employeeGroup.getGroupName());
			tempDateTime = beginDateTime;
			List<Integer> xData = new ArrayList<Integer>();
			tempDateTime = beginDateTime;
			Integer yearInverstor = groupStatsServiceImpl.queryGroupinvestorPerformanceYear(
					groupIdList.get(i), tempDateTime.toString(formatterYear));
			xData.add(yearInverstor);
			tempDateTime = tempDateTime.plusYears(1);
			while ((tempDateTime.toString(formatterYear).compareTo(
					endDateTime.toString(formatterYear)) <= 0)) {
				yearInverstor = groupStatsServiceImpl.queryGroupinvestorPerformanceYear(
						groupIdList.get(i), tempDateTime.toString(formatterYear));
				xData.add(yearInverstor);
				tempDateTime = tempDateTime.plusYears(1);
			}
			Series line = new Line().smooth(true).name(employeeGroup.getGroupName())
					.symbol(Symbol.circle).data(xData.toArray());
			lines2.add(line);
		}
		Option option2 = new Option();
		option2.title().text("新增投资人统计");
		option2.tooltip().trigger(Trigger.axis);
		option2.toolbox().show(true).feature(Tool.saveAsImage);
		option2.calculable(true);
		option2.legend(legend2.toArray());
		CategoryAxis xAxis2 = new CategoryAxis().data(xList.toArray()).name("日期");
		option2.xAxis(xAxis2);
		ValueAxis yAxis2 = new ValueAxis().name("新增投资人数（个）");
		option2.yAxis(yAxis2);
		option2.series(lines2);

		// 团队新增预约数统计“曲线”
		List<Series> lines3 = new ArrayList<Series>();
		List<String> legend3 = new ArrayList<String>();
		for (int i = 0; i < groupIdList.size(); i++) {
			EmployeeGroup employeeGroup = employeeGroupServiceImpl.get(groupIdList.get(i));
			legend3.add(employeeGroup.getGroupName());
			tempDateTime = beginDateTime;
			List<Integer> xData = new ArrayList<Integer>();
			tempDateTime = beginDateTime;
			Integer yearAppointment = groupStatsServiceImpl.queryGroupAppointmentPerformanceYear(
					groupIdList.get(i), tempDateTime.toString(formatterYear));
			xData.add(yearAppointment);
			tempDateTime = tempDateTime.plusYears(1);
			while ((tempDateTime.toString(formatterYear).compareTo(
					endDateTime.toString(formatterYear)) <= 0)) {
				yearAppointment = groupStatsServiceImpl.queryGroupAppointmentPerformanceYear(
						groupIdList.get(i), tempDateTime.toString(formatterYear));
				xData.add(yearAppointment);
				tempDateTime = tempDateTime.plusYears(1);
			}
			Series line = new Line().smooth(true).name(employeeGroup.getGroupName())
					.symbol(Symbol.circle).data(xData.toArray());
			lines3.add(line);
		}
		Option option3 = new Option();
		option3.title().text("新增预约统计");
		option3.tooltip().trigger(Trigger.axis);
		option3.toolbox().show(true).feature(Tool.saveAsImage);
		option3.calculable(true);
		option3.legend(legend3.toArray());
		CategoryAxis xAxis3 = new CategoryAxis().data(xList.toArray()).name("日期");
		xAxis3.name("时间");
		option3.xAxis(xAxis3);
		ValueAxis yAxis3 = new ValueAxis().name("新增预约数");
		yAxis3.name("预约数（个）");
		option3.yAxis(yAxis3);
		option3.series(lines3);

		List<Option> optionList = new ArrayList<Option>();
		optionList.add(option);
		optionList.add(option2);
		optionList.add(option3);
		return optionList;
	}

	private List<Option> queryGroupPerformanceMonth(DateTime beginDateTime, DateTime endDateTime,
			ArrayList<String> groupIdList) {
		// 时间“x轴”
		DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM");

		List<String> xDateList = new ArrayList<String>();
		DateTime tempDateTime = beginDateTime;

		xDateList.add(tempDateTime.toString(formatter));
		tempDateTime = tempDateTime.plusMonths(1);
		while ((tempDateTime.toString(formatter).compareTo(endDateTime.toString(formatter)) <= 0)) {
			xDateList.add(tempDateTime.toString(formatter));
			tempDateTime = tempDateTime.plusMonths(1);
		}
		LOGGER.info("groupStats querDay xDateList = [{}]", xDateList);
		// 团队业绩数据“曲线”
		List<Series> lines = new ArrayList<Series>();// 曲线
		List<String> legend = new ArrayList<String>();// 每个团队的名字
		for (int i = 0; i < groupIdList.size(); i++) {
			tempDateTime = beginDateTime;
			List<Double> xData = new ArrayList<Double>();
			Double sum = 0D;
			Map<String, Object> map = groupStatsServiceImpl.queryGroupSalesPerformance(
					groupIdList.get(i), tempDateTime.toString(formatter));
			List<Double> redisData = (List<Double>) map.get("data");
			for (Double double1 : redisData) {
				sum = BigDecimalUtils.add(sum, double1);
			}
			xData.add(BigDecimalUtils.divide(sum, 10000D, 2));
			String name = (String) map.get("name");
			legend.add(name);
			tempDateTime = tempDateTime.plusMonths(1);
			while ((tempDateTime.toString(formatter).compareTo(endDateTime.toString(formatter)) <= 0)) {
				sum = 0D;
				map = groupStatsServiceImpl.queryGroupSalesPerformance(groupIdList.get(i),
						tempDateTime.toString(formatter));
				redisData = (List<Double>) map.get("data");
				for (Double double1 : redisData) {
					sum = BigDecimalUtils.add(sum, double1);
				}
				xData.add(BigDecimalUtils.divide(sum, 10000D, 2));
				tempDateTime = tempDateTime.plusMonths(1);
			}
			Series line = new Line().smooth(true).name(name).symbol(Symbol.circle)
					.data(xData.toArray());
			lines.add(line);
		}
		// 封装option
		Option option = new Option();
		option.title().text("销售业绩统计");
		option.tooltip().trigger(Trigger.axis);
		option.toolbox().show(true).feature(Tool.saveAsImage);
		option.calculable(true);
		option.legend(legend.toArray());
		CategoryAxis xAxis = new CategoryAxis().boundaryGap(false).data(xDateList.toArray()).name("时间");
		option.xAxis(xAxis);
		ValueAxis yAxis = new ValueAxis().name("销售业绩（万元）");
		option.yAxis(yAxis);
		option.series(lines);

		// 团队新增投资人数据“曲线”
		List<Series> lines2 = new ArrayList<Series>();
		List<String> legend2 = new ArrayList<String>();
		for (int i = 0; i < groupIdList.size(); i++) {
			tempDateTime = beginDateTime;
			List<Integer> xData = new ArrayList<Integer>();
			Integer sum = 0;
			Map<String, Object> map = groupStatsServiceImpl.queryGroupinvestorPerformance(
					groupIdList.get(i), tempDateTime.toString(formatter));
			List<Integer> redisData = (List<Integer>) map.get("data");
			for (Integer integer : redisData) {
				sum = sum + integer;
			}
			xData.add(sum);
			String name = (String) map.get("name");
			legend2.add(name);
			tempDateTime = tempDateTime.plusMonths(1);
			while ((tempDateTime.toString(formatter).compareTo(endDateTime.toString(formatter)) <= 0)) {
				sum = 0;
				map = groupStatsServiceImpl.queryGroupinvestorPerformance(groupIdList.get(i),
						tempDateTime.toString(formatter));
				redisData = (List<Integer>) map.get("data");
				for (Integer integer : redisData) {
					sum = sum + integer;
				}
				xData.add(sum);
				tempDateTime = tempDateTime.plusMonths(1);
			}
			Series line = new Line().smooth(true).name(name).symbol(Symbol.circle)
					.data(xData.toArray());
			lines2.add(line);
		}
		Option option2 = new Option();
		option2.title().text("新增投资人统计");
		option2.tooltip().trigger(Trigger.axis);
		option2.toolbox().show(true).feature(Tool.saveAsImage);
		option2.calculable(true);
		option2.legend(legend2.toArray());
		CategoryAxis xAxis2 = new CategoryAxis().boundaryGap(false).data(xDateList.toArray()).name("时间");
		option2.xAxis(xAxis2);
		ValueAxis yAxis2 = new ValueAxis().name("新增投资人数（个）");
		option2.yAxis(yAxis2);
		option2.series(lines2);

		// 团队新增预约数统计“曲线”
		List<Series> lines3 = new ArrayList<Series>();
		List<String> legend3 = new ArrayList<String>();
		for (int i = 0; i < groupIdList.size(); i++) {
			tempDateTime = beginDateTime;
			List<Integer> xData = new ArrayList<Integer>();
			Integer sum = 0;
			Map<String, Object> map = groupStatsServiceImpl.queryGroupAppointmentPerformance(
					groupIdList.get(i), tempDateTime.toString(formatter));
			List<Integer> redisData = (List<Integer>) map.get("data");
			for (Integer integer : redisData) {
				sum = sum + integer;
			}
			xData.add(sum);
			String name = (String) map.get("name");
			legend3.add(name);
			tempDateTime = tempDateTime.plusMonths(1);
			while ((tempDateTime.toString(formatter).compareTo(endDateTime.toString(formatter)) <= 0)) {
				sum = 0;
				map = groupStatsServiceImpl.queryGroupAppointmentPerformance(groupIdList.get(i),
						tempDateTime.toString(formatter));
				redisData = (List<Integer>) map.get("data");
				for (Integer integer : redisData) {
					sum = sum + integer;
				}
				xData.add(sum);
				tempDateTime = tempDateTime.plusMonths(1);
			}
			Series line = new Line().smooth(true).name(name).symbol(Symbol.circle)
					.data(xData.toArray());
			lines3.add(line);
		}
		Option option3 = new Option();
		option3.title().text("新增预约统计");
		option3.tooltip().trigger(Trigger.axis);
		option3.toolbox().show(true).feature(Tool.saveAsImage);
		option3.calculable(true);
		option3.legend(legend3.toArray());
		CategoryAxis xAxis3 = new CategoryAxis().boundaryGap(false).data(xDateList.toArray());
		xAxis3.name("时间");
		option3.xAxis(xAxis3);
		ValueAxis yAxis3 = new ValueAxis();
		yAxis3.name("预约数（个）");
		option3.yAxis(yAxis3);
		option3.series(lines3);

		List<Option> optionList = new ArrayList<Option>();
		optionList.add(option);
		optionList.add(option2);
		optionList.add(option3);
		return optionList;
	}

	private List<Option> queryGroupPerformance(DateTime beginDateTime, DateTime endDateTime,
			ArrayList<String> groupIdList) {
		// 时间“x轴”
		int beginDay = beginDateTime.getDayOfMonth();
		int endDay = endDateTime.getDayOfMonth();
		int days = Days.daysBetween(beginDateTime, endDateTime).getDays();
		List<String> xDateList = new ArrayList<String>();
		DateTime tempDateTime = beginDateTime;
		for (int i = 0; i <= days; i++) {
			xDateList.add(tempDateTime.toString("yyyy-MM-dd"));
			tempDateTime = tempDateTime.plusDays(1);
		}
		LOGGER.info("groupStats querDay xDateList = [{}]", xDateList);
		// 团队业绩数据“曲线”
		// 先查看缓存，有对应的数据则从缓存中读取，没有则从数据库中读取并存缓存。
		DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM");
		boolean months = beginDateTime.toString(formatter).equals(endDateTime.toString(formatter));
		List<Series> lines = new ArrayList<Series>();
		List<String> legend = new ArrayList<String>();
		if (months) {// 开始时间和结束时间再同一个月
			for (int i = 0; i < groupIdList.size(); i++) {
				Map<String, Object> map = groupStatsServiceImpl.queryGroupSalesPerformance(
						groupIdList.get(i), beginDateTime.toString(formatter));
				List<Double> xData = new ArrayList<Double>();
				List<Double> redisData = (List<Double>) map.get("data");
				for (int j = beginDay; j <= endDay; j++) {
					xData.add(BigDecimalUtils.divide(redisData.get(j - 1), 10000D, 2));
				}
				Series line = new Line().smooth(true).name((String) map.get("name"))
						.symbol(Symbol.circle).data(xData.toArray());
				lines.add(line);
				legend.add((String) map.get("name"));
			}
		} else {// 开始时间和结束时间不在同一个月
			for (int i = 0; i < groupIdList.size(); i++) {
				List<Double> xData = new ArrayList<Double>();
				// 前一个月
				Map<String, Object> map = groupStatsServiceImpl.queryGroupSalesPerformance(
						groupIdList.get(i), beginDateTime.toString(formatter));
				List<Double> redisData = (List<Double>) map.get("data");
				int size = redisData.size();
				for (int j = beginDay; j <= size; j++) {
					xData.add(BigDecimalUtils.divide(redisData.get(j - 1), 10000D, 2));
				}
				// 后一个月
				map = groupStatsServiceImpl.queryGroupSalesPerformance(groupIdList.get(i),
						endDateTime.toString(formatter));
				redisData = (List<Double>) map.get("data");
				for (int j = 1; j <= endDay; j++) {
					xData.add(BigDecimalUtils.divide(redisData.get(j - 1), 10000D, 2));
				}
				Series line = new Line().smooth(true).name((String) map.get("name"))
						.symbol(Symbol.circle).data(xData.toArray());
				lines.add(line);
				legend.add((String) map.get("name"));
			}
		}
		// 封装option
		Option option = new Option();
		option.title().text("销售业绩统计");
		option.tooltip().trigger(Trigger.axis);
		option.toolbox().show(true).feature(Tool.saveAsImage);
		option.calculable(true);
		option.legend(legend.toArray());
		CategoryAxis xAxis = new CategoryAxis().boundaryGap(false).data(xDateList.toArray());
		xAxis.name("时间");
		option.xAxis(xAxis);

		ValueAxis yAxis = new ValueAxis();
		// AxisLabel label = new AxisLabel();
		// label.formatter("");
		// yAxis.axisLabel(label);
		yAxis.name("销售业绩（万元）");
		option.yAxis(yAxis);
		option.series(lines);

		// 团队新增投资人数据“曲线”
		List<Series> lines2 = new ArrayList<Series>();
		List<String> legend2 = new ArrayList<String>();
		if (months) {// 开始时间和结束时间再同一个月
			for (int i = 0; i < groupIdList.size(); i++) {
				Map<String, Object> map = groupStatsServiceImpl.queryGroupinvestorPerformance(
						groupIdList.get(i), beginDateTime.toString(formatter));
				List<Integer> xData = new ArrayList<Integer>();
				List<Integer> redisData = (List<Integer>) map.get("data");
				for (int j = beginDay; j <= endDay; j++) {
					xData.add(redisData.get(j - 1));
				}
				Series line = new Line().smooth(true).name((String) map.get("name"))
						.symbol(Symbol.circle).data(xData.toArray());
				lines2.add(line);
				legend2.add((String) map.get("name"));
			}
		} else {// 开始时间和结束时间不在同一个月
			for (int i = 0; i < groupIdList.size(); i++) {
				List<Integer> xData = new ArrayList<Integer>();
				// 前一个月
				Map<String, Object> map = groupStatsServiceImpl.queryGroupinvestorPerformance(
						groupIdList.get(i), beginDateTime.toString(formatter));
				List<Integer> redisData = (List<Integer>) map.get("data");
				int size = redisData.size();
				for (int j = beginDay; j <= size; j++) {
					xData.add(redisData.get(j - 1));
				}
				// 后一个月
				map = groupStatsServiceImpl.queryGroupinvestorPerformance(groupIdList.get(i),
						endDateTime.toString(formatter));
				redisData = (List<Integer>) map.get("data");
				for (int j = 1; j <= endDay; j++) {
					xData.add(redisData.get(j - 1));
				}
				Series line2 = new Line().smooth(true).name((String) map.get("name"))
						.symbol(Symbol.circle).data(xData.toArray());
				lines2.add(line2);
				legend2.add((String) map.get("name"));
			}
		}
		Option option2 = new Option();
		option2.title().text("新增投资人统计");
		option2.tooltip().trigger(Trigger.axis);
		option2.toolbox().show(true).feature(Tool.saveAsImage);
		option2.calculable(true);
		option2.legend(legend2.toArray());
		CategoryAxis xAxis2 = new CategoryAxis().boundaryGap(false).data(xDateList.toArray());
		xAxis2.name("时间");
		option2.xAxis(xAxis2);
		ValueAxis yAxis2 = new ValueAxis();
		yAxis2.name("新增投资人数（个）");
		option2.yAxis(yAxis2);
		option2.series(lines2);

		// 团队新增预约数统计“曲线”
		List<Series> lines3 = new ArrayList<Series>();
		List<String> legend3 = new ArrayList<String>();
		if (months) {// 开始时间和结束时间再同一个月
			for (int i = 0; i < groupIdList.size(); i++) {
				Map<String, Object> map = groupStatsServiceImpl.queryGroupAppointmentPerformance(
						groupIdList.get(i), beginDateTime.toString(formatter));
				List<Integer> xData = new ArrayList<Integer>();
				List<Integer> redisData = (List<Integer>) map.get("data");
				for (int j = beginDay; j <= endDay; j++) {
					xData.add(redisData.get(j - 1));
				}
				Series line = new Line().smooth(true).name((String) map.get("name"))
						.symbol(Symbol.circle).data(xData.toArray());
				lines3.add(line);
				legend3.add((String) map.get("name"));
			}
		} else {// 开始时间和结束时间不在同一个月
			for (int i = 0; i < groupIdList.size(); i++) {
				List<Integer> xData = new ArrayList<Integer>();
				// 前一个月
				Map<String, Object> map = groupStatsServiceImpl.queryGroupAppointmentPerformance(
						groupIdList.get(i), beginDateTime.toString(formatter));
				List<Integer> redisData = (List<Integer>) map.get("data");
				int size = redisData.size();
				for (int j = beginDay; j <= size; j++) {
					xData.add(redisData.get(j - 1));
				}
				// 后一个月
				map = groupStatsServiceImpl.queryGroupAppointmentPerformance(groupIdList.get(i),
						endDateTime.toString(formatter));
				redisData = (List<Integer>) map.get("data");
				for (int j = 1; j <= endDay; j++) {
					xData.add(redisData.get(j - 1));
				}
				Series line = new Line().smooth(true).name((String) map.get("name"))
						.symbol(Symbol.circle).data(xData.toArray());
				lines3.add(line);
				legend3.add((String) map.get("name"));
			}
		}
		Option option3 = new Option();
		option3.title().text("新增预约统计");
		option3.tooltip().trigger(Trigger.axis);
		option3.toolbox().show(true).feature(Tool.saveAsImage);
		option3.calculable(true);
		option3.legend(legend3.toArray());
		CategoryAxis xAxis3 = new CategoryAxis().boundaryGap(false).data(xDateList.toArray());
		xAxis3.name("时间");
		option3.xAxis(xAxis3);
		ValueAxis yAxis3 = new ValueAxis();
		yAxis3.name("预约数（个）");
		option3.yAxis(yAxis3);
		option3.series(lines3);

		List<Option> optionList = new ArrayList<Option>();
		optionList.add(option);
		optionList.add(option2);
		optionList.add(option3);
		return optionList;
	}
}
